﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OhalcLib;
using System.Globalization;
using System.IO;
using System.Threading;

namespace Ohalc_WinForms
{
    public partial class MainForm : Form
    {
        public List<Session> sessions = new List<Session>();
        BindingList<Session> sessionsForGrid = new BindingList<Session>();
        public List<Tick> ticks = new List<Tick>();
        public List<Trade> trades = new List<Trade>();
        public List<Tick> HTicks = new List<Tick>();

        private Decimal takeProfit = Math.Round(Convert.ToDecimal("0,00200"), 5);
        private Decimal stopLoss = Math.Round(Convert.ToDecimal("0,01000"), 5);

        private int CurrentTickCount = 0;

        public Trade CurrentTrade { get; set; }

        private Tick prevHCandle;
        public Tick PrevHCandle
        {
            get
            {
                if (HTicks.Count >= 2)
                {
                    return HTicks[HTicks.Count - 2];
                }
                else
                    return null;

            }
            //get;
            //set;
        }

        private Tick currectHCandle;
        public Tick CurrentHCandle 
        {
            get
            {
                if (HTicks.Count >= 1)
                {
                    return HTicks[HTicks.Count - 1];
                }
                else
                    return null;

            }
            //get; set; 
        }


        public MainForm()
        {
            InitializeComponent();

            BaseInit();
            
        }

        public void BaseInit()
        {
            string filePath = "EURUSD5_newAlpari.csv";
            string line = "";
            //Tick[] ticks=new Tick[];


            if (File.Exists(filePath))
            {
                Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

                StreamReader file = new StreamReader(filePath);
                string[] splitter = new string[] { "," };

                string[] objs;
                Tick tick = new Tick();

                int e = 0;
                while ((line = file.ReadLine()) != null)
                {
                    objs = line.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
                    tick = new Tick();

                    tick.Time = Convert.ToDateTime(String.Format("{0} {1}", objs[0], objs[1]));
                    tick.Open = Math.Round(Convert.ToDecimal(objs[2]), 5);
                    tick.High = Math.Round(Convert.ToDecimal(objs[3]), 5);
                    tick.Low = Math.Round(Convert.ToDecimal(objs[4]), 5);
                    tick.Close = Math.Round(Convert.ToDecimal(objs[5]), 5);

                    if(tick.Open>tick.Close)
                        tick.Direction=Direction.DOWN;
                    if(tick.Open<tick.Close)
                        tick.Direction=Direction.UP;
                    if(tick.Open==tick.Close)
                        tick.Direction=Direction.DODGE;

                    tick.BodyWidth = Math.Round((Math.Abs(tick.Open - tick.Close) * 10000), 2);
                    //if(e<1000)
                    ticks.Add(tick);
                    //Console.WriteLine(line);
                    e++;
                }

                Stream stream = File.Open("Ticks.xml", FileMode.Create);

                System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(ticks.GetType());
                x.Serialize(stream, ticks);
                stream.Close();


                #region Marat KiS
                //DateTime curDate = ticks[0].Time.Date;



                //TimeSpan jpStart = new TimeSpan(1, 0, 0);
                //TimeSpan jpEnd = new TimeSpan(7, 55, 0);
                //TimeSpan euStart = new TimeSpan(8, 0, 0);
                //TimeSpan euEnd = new TimeSpan(15, 25, 0);
                //TimeSpan usStart = new TimeSpan(15, 30, 0);
                //TimeSpan usEnd = new TimeSpan(22, 55, 0);

                //decimal open = 0;
                //SessionPoint high = new SessionPoint();
                //SessionPoint low = new SessionPoint();
                //decimal close = 0;

                //Session session = new Session();

                //if (ticks[0].Time.TimeOfDay >= jpStart && ticks[0].Time.TimeOfDay <= jpEnd)
                //{
                //    open = ticks[0].Open;
                //    high.Point = ticks[0].Open;
                //    high.TimeOfDay = ticks[0].Time.TimeOfDay;
                //    low.Point = ticks[0].Open;
                //    low.TimeOfDay = ticks[0].Time.TimeOfDay;
                //}
                //if (ticks[0].Time.TimeOfDay >= euStart && ticks[0].Time.TimeOfDay <= euEnd)
                //{
                //    open = ticks[0].Open;
                //    high.Point = ticks[0].Open;
                //    high.TimeOfDay = ticks[0].Time.TimeOfDay;
                //    low.Point = ticks[0].Open;
                //    low.TimeOfDay = ticks[0].Time.TimeOfDay;
                //}
                //if (ticks[0].Time.TimeOfDay >= usStart && ticks[0].Time.TimeOfDay <= usEnd)
                //{
                //    open = ticks[0].Open;
                //    high.Point = ticks[0].Open;
                //    high.TimeOfDay = ticks[0].Time.TimeOfDay;
                //    low.Point = ticks[0].Open;
                //    low.TimeOfDay = ticks[0].Time.TimeOfDay;
                //}


                //DateTime changeGTTime = new DateTime(2011, 4, 30, 0, 0, 0);
                #endregion

                #region Trading Andrey Ukraine 20 profit 100 loss
                //List<TimeSpan> listWHoursEnd = new List<TimeSpan>();
                //listWHoursEnd.Add(new TimeSpan(10, 00, 00));
                //listWHoursEnd.Add(new TimeSpan(11, 00, 00));
                //listWHoursEnd.Add(new TimeSpan(12, 00, 00));
                //listWHoursEnd.Add(new TimeSpan(13, 00, 00));
                //listWHoursEnd.Add(new TimeSpan(14, 00, 00));
                //listWHoursEnd.Add(new TimeSpan(15, 00, 00));
                //listWHoursEnd.Add(new TimeSpan(16, 00, 00));
                //listWHoursEnd.Add(new TimeSpan(17, 00, 00));
                //listWHoursEnd.Add(new TimeSpan(18, 00, 00));
                //listWHoursEnd.Add(new TimeSpan(19, 00, 00));
                //listWHoursEnd.Add(new TimeSpan(20, 00, 00));

                //List<TimeSpan> listWHoursStart = new List<TimeSpan>();
                //listWHoursStart.Add(new TimeSpan(12, 00, 00));
                //listWHoursStart.Add(new TimeSpan(13, 00, 00));
                //listWHoursStart.Add(new TimeSpan(14, 00, 00));
                //listWHoursStart.Add(new TimeSpan(15, 00, 00));
                //listWHoursStart.Add(new TimeSpan(16, 00, 00));
                //listWHoursStart.Add(new TimeSpan(17, 00, 00));
                //listWHoursStart.Add(new TimeSpan(18, 00, 00));
                //listWHoursStart.Add(new TimeSpan(19, 00, 00));
                //listWHoursStart.Add(new TimeSpan(20, 00, 00));

                //DateTime fromToTest = new DateTime(2010, 10, 07);
                #endregion

                #region Gaps

                List<Gap> gaps=new List<Gap>();
                Gap currentGap=new Gap();

                bool firstGap = true;
                bool gapOpenDay = false;

                //Alpari
                TimeSpan timeBefore = new TimeSpan(23, 55, 0);
                TimeSpan timeOnOpen = new TimeSpan(1, 0, 0);

                //Fibo
                //TimeSpan timeBefore = new TimeSpan(21, 55, 0); 
                //TimeSpan timeOnOpen = new TimeSpan(22, 0, 0);

                Decimal pullback = 0;
                Decimal shadowPullback = 0;

                int point = 10000;

                #endregion

                for (int i = 0; i < ticks.Count; i++)
                {
                    #region Check for OHALC (KIS_Marat)
                    //if (ticks[i].Time > changeGTTime)
                    //{
                    //    jpStart = new TimeSpan(2, 0, 0);
                    //    jpEnd = new TimeSpan(8, 55, 0);
                    //    euStart = new TimeSpan(9, 0, 0);
                    //    euEnd = new TimeSpan(16, 25, 0);
                    //    usStart = new TimeSpan(16, 30, 0);
                    //    usEnd = new TimeSpan(22, 55, 0);
                    //}

                    //if (i == ticks.Count - 13)
                    //{
                    //    int j = i;
                    //}

                    //if (high.Point < ticks[i].High)
                    //{
                    //    high.Point = ticks[i].High;
                    //    high.TimeOfDay = ticks[i].Time.TimeOfDay;
                    //}

                    //if (low.Point > ticks[i].Low)
                    //{
                    //    low.Point = ticks[i].Low;
                    //    low.TimeOfDay = ticks[i].Time.TimeOfDay;
                    //}

                    //if (ticks[i].Time.TimeOfDay == jpStart)
                    //{
                    //    session = new Session();
                    //    open = ticks[i].Open;
                    //    high = new SessionPoint();
                    //    low = new SessionPoint();
                    //    high.Point = ticks[i].Open;
                    //    high.TimeOfDay = ticks[i].Time.TimeOfDay;
                    //    low.Point = ticks[i].Open;
                    //    low.TimeOfDay = ticks[i].Time.TimeOfDay;
                    //    close = 0;
                    //}
                    //if (ticks[i].Time.TimeOfDay == jpEnd)
                    //{
                    //    close = ticks[i].Close;
                    //    MakeSession(i, "jp", session, ticks, sessions, open, high, low, close);
                        
                    //}
                    //if (ticks[i].Time.TimeOfDay == euStart)
                    //{
                    //    session = new Session();
                    //    open = ticks[i].Open;
                    //    high = new SessionPoint();
                    //    low = new SessionPoint();
                    //    high.Point = ticks[i].Open;
                    //    high.TimeOfDay = ticks[i].Time.TimeOfDay;
                    //    low.Point = ticks[i].Open;
                    //    low.TimeOfDay = ticks[i].Time.TimeOfDay;
                    //    close = 0;
                    //}
                    //if (ticks[i].Time.TimeOfDay == euEnd)
                    //{
                    //    close = ticks[i].Close;
                    //    MakeSession(i, "eu", session, ticks, sessions, open, high, low, close);
                        
                    //}
                    //if (ticks[i].Time.TimeOfDay == usStart)
                    //{
                    //    session = new Session();
                    //    open = ticks[i].Open;
                    //    high = new SessionPoint();
                    //    low = new SessionPoint();
                    //    high.Point = ticks[i].Open;
                    //    high.TimeOfDay = ticks[i].Time.TimeOfDay;
                    //    low.Point = ticks[i].Open;
                    //    low.TimeOfDay = ticks[i].Time.TimeOfDay;
                    //    close = 0;
                    //}
                    //if (ticks[i].Time.TimeOfDay == usEnd)
                    //{
                    //    close = ticks[i].Close;
                    //    MakeSession(i, "us", session, ticks, sessions, open, high, low, close);

                    //}
                    #endregion

                    #region Trading Andrey Ukraine 20 profit 100 loss
                    //if (ticks[i].Time < fromToTest)
                    //    continue;

                    //if (listWHoursEnd.Any(p => p.ToString() == ticks[i].Time.TimeOfDay.ToString()))
                    //{
                    //    Tick HCandle = new Tick();
                    //    if (i - 1 >= 0)
                    //    {
                    //        HCandle.Close = ticks[i-1].Close;
                    //        HCandle.High = 0;
                    //        HCandle.Low = 0;
                    //    }
                    //    else
                    //        HCandle = null;

                    //    //if (HTicks.Count > 0 && HTicks[HTicks.Count - 1]!=null)
                    //    //    HCandle.Close = HTicks[HTicks.Count - 1].Open;
                    //    //else
                    //    //{
                    //    //    if (i > 11)
                    //    //        HCandle.Close = ticks[i - 11].Open;
                    //    //    else
                    //    //        HCandle = null;
                    //    //}

                    //    if (i - 12>=0 && HCandle!=null)
                    //    {
                    //        HCandle.Open = ticks[i -12].Open;
                    //        HCandle.Time = ticks[i-12].Time;
                    //    }
                    //    else
                    //        HCandle = null;

                    //    if (HCandle != null)
                    //    {
                    //        HCandle.BodyWidth = Math.Round((Math.Abs(HCandle.Open - HCandle.Close) * 10000), 2);

                    //        if (HCandle.Open > HCandle.Close)
                    //            HCandle.Direction = Direction.DOWN;
                    //        if (HCandle.Open < HCandle.Close)
                    //            HCandle.Direction = Direction.UP;
                    //        if (HCandle.Open == HCandle.Close)
                    //            HCandle.Direction = Direction.DODGE;
                    //    }

                    //    HTicks.Add(HCandle);
                    //}

                    //if (listWHoursStart.Any(p => p.ToString() == ticks[i].Time.TimeOfDay.ToString()))
                    //{
                    //    if (CurrentTrade == null)//check weather to open trade
                    //    {
                    //        if (PrevHCandle != null && CurrentHCandle != null)
                    //        {
                    //            if ((PrevHCandle.Direction == CurrentHCandle.Direction &&
                    //                PrevHCandle.BodyWidth > 5 && CurrentHCandle.BodyWidth > 5 && CurrentHCandle.Direction!=Direction.DODGE)
                    //                || (PrevHCandle.Direction != CurrentHCandle.Direction && PrevHCandle.Direction != Direction.DODGE && CurrentHCandle.Direction != Direction.DODGE && PrevHCandle.BodyWidth<CurrentHCandle.BodyWidth&& 
                    //                    PrevHCandle.BodyWidth>5 && CurrentHCandle.BodyWidth>5))
                    //            {
                    //                Trade newTrade = new Trade();
                    //                newTrade.OpenTime = ticks[i].Time;
                    //                newTrade.OpenPrice = ticks[i].Open;
                    //                newTrade.TradeDirection=CurrentHCandle.Direction;

                    //                CurrentTrade = newTrade;
                    //            }
                    //        }
                    //    }
                    //}

                    //if (CurrentTrade != null)
                    //{
                    //    bool closeTrade = false;
                    //    if (CurrentTrade.TradeDirection == Direction.DOWN)
                    //    {
                    //        if (ticks[i].Low < (CurrentTrade.OpenPrice - takeProfit) && ticks[i].High > (CurrentTrade.OpenPrice + stopLoss))
                    //        {
                    //            CurrentTrade.Result = 0;
                    //            closeTrade = true;
                    //        }
                    //        else
                    //        {
                    //            if (ticks[i].Low < (CurrentTrade.OpenPrice - takeProfit))
                    //            {
                    //                CurrentTrade.Result = takeProfit;
                    //                closeTrade = true;
                    //            }
                    //            if (ticks[i].High > (CurrentTrade.OpenPrice + stopLoss))
                    //            {
                    //                CurrentTrade.Result =0- stopLoss;
                    //                closeTrade = true;
                    //            }
                    //        }
                    //    }

                    //    if (CurrentTrade.TradeDirection == Direction.UP)
                    //    {
                    //        Decimal r = CurrentTrade.OpenPrice + takeProfit;
                    //        if (ticks[i].Low < (CurrentTrade.OpenPrice - stopLoss) && ticks[i].High > (CurrentTrade.OpenPrice + takeProfit))
                    //        {
                    //            CurrentTrade.Result = 0;
                    //            closeTrade = true;
                    //        }
                    //        else
                    //        {
                    //            if (ticks[i].Low < (CurrentTrade.OpenPrice - stopLoss))
                    //            {
                    //                CurrentTrade.Result =0- stopLoss;
                    //                closeTrade = true;
                    //            }
                    //            if (ticks[i].High > (CurrentTrade.OpenPrice + takeProfit))
                    //            {
                    //                CurrentTrade.Result = takeProfit;
                    //                closeTrade = true;
                    //            }
                    //        }
                    //    }

                    //    if (closeTrade)
                    //    {
                    //        CurrentTrade.CloseTime = ticks[i].Time;
                    //        trades.Add(CurrentTrade);
                    //        CurrentTrade = null;
                    //    }
                    //}
                    #endregion

                    #region Gaps
                    

                    //if (ticks[i].Time.TimeOfDay == timeBefore && ticks[i].Time.DayOfWeek == DayOfWeek.Friday)
                    //{
                    //    if (!firstGap && currentGap!=null)
                    //    {
                    //        gaps.Add(currentGap);//gap have not closed in a week. Very bad situation
                    //        currentGap = null;
                    //    }


                    //    currentGap = new Gap();
                    //    currentGap.GapDate = ticks[i].Time;
                    //    currentGap.PriceBeforeOpen = ticks[i].Close;

                    //    gapOpenDay = true;

                    //    firstGap = false;
                    //}

                    if (ticks[i].Time.TimeOfDay == timeOnOpen && ticks[i].Time.DayOfWeek == DayOfWeek.Monday )//&& currentGap != null && gapOpenDay == true)
                    {
                        if (currentGap != null)
                        {
                            gaps.Add(currentGap);//gap have not closed in a week. Very bad situation
                            currentGap = null;
                        }

                        currentGap = new Gap();
                        currentGap.GapDate = ticks[i-1].Time;
                        currentGap.PriceBeforeOpen = ticks[i-1].Close;


                        currentGap.PriceAfterOpen = ticks[i].Open;


                        if ((currentGap.PriceAfterOpen - currentGap.PriceBeforeOpen) > 0)
                        {
                            currentGap.GapTo = GapDirection.UP;
                            currentGap.PriceOfShadowToGap = ticks[i-1].High;
                        }

                        if ((currentGap.PriceAfterOpen - currentGap.PriceBeforeOpen) < 0)
                        {
                            currentGap.GapTo = GapDirection.DOWN;
                            currentGap.PriceOfShadowToGap = ticks[i - 1].Low;
                        }

                        if ((currentGap.PriceAfterOpen - currentGap.PriceBeforeOpen) == 0)
                        {
                            currentGap.GapTo = GapDirection.DODGE;
                            currentGap.PriceOfShadowToGap = ticks[i - 1].Close;
                        }

                        currentGap.GapWidth = Math.Round((Math.Abs(currentGap.PriceAfterOpen - currentGap.PriceBeforeOpen) * point), 2);
                        currentGap.GapToShadowWidth = Math.Round((Math.Abs(currentGap.PriceAfterOpen - currentGap.PriceOfShadowToGap) * point), 2);

                        currentGap.PullbackPoints = 0;
                        currentGap.GapToShadowPullbackPoints = 0;

                        gapOpenDay = false;
                    }

                    if (currentGap != null)
                    {
                        if (currentGap.PriceAfterOpen > 0)
                        {
                            if (currentGap.GapTo == GapDirection.DOWN)
                            {
                                pullback = Math.Abs(ticks[i].Low - currentGap.PriceAfterOpen) * point;

                                if (pullback > currentGap.PullbackPoints)
                                    currentGap.PullbackPoints = pullback;

                                if (pullback > currentGap.GapToShadowPullbackPoints && currentGap.GapToShadowGapCloseDate==DateTime.MinValue)
                                    currentGap.GapToShadowPullbackPoints = pullback;

                                if (ticks[i].High >= currentGap.PriceOfShadowToGap)
                                {
                                    currentGap.GapToShadowGapCloseDate = ticks[i].Time;
                                }

                                if (ticks[i].High >= currentGap.PriceBeforeOpen)
                                {
                                    currentGap.GapCloseDate = ticks[i].Time;
                                    currentGap.GapDurationBeforeClose = ticks[i].Time - currentGap.GapDate;
                                    gaps.Add(currentGap);
                                    currentGap = null;
                                }

                                
                            }
                            else
                            {
                                if (currentGap.GapTo == GapDirection.UP)
                                {
                                    pullback = Math.Abs(ticks[i].High - currentGap.PriceAfterOpen) * point;

                                    if (pullback > currentGap.PullbackPoints)
                                        currentGap.PullbackPoints = pullback;

                                    if (pullback > currentGap.GapToShadowPullbackPoints && currentGap.GapToShadowGapCloseDate == DateTime.MinValue)
                                        currentGap.GapToShadowPullbackPoints = pullback;

                                    if (ticks[i].Low <= currentGap.PriceOfShadowToGap)
                                    {
                                        currentGap.GapToShadowGapCloseDate = ticks[i].Time;
                                    }

                                    if (ticks[i].Low <= currentGap.PriceBeforeOpen)
                                    {
                                        currentGap.GapCloseDate = ticks[i].Time;
                                        currentGap.GapDurationBeforeClose = ticks[i].Time - currentGap.GapDate;
                                        gaps.Add(currentGap);
                                        currentGap = null;
                                    }

                                    
                                }
                            }
                        }
                    }

                    #endregion

                }

                

                #region Check for KIS Marat
                //Stream stream1 = File.Open("Sessions.xml", FileMode.Create);

                //System.Xml.Serialization.XmlSerializer x1 = new System.Xml.Serialization.XmlSerializer(sessions.GetType());
                //x1.Serialize(stream1, sessions);
                //stream1.Close();

                //grv_Sessions.DataSource = sessionsForGrid;
                #endregion

                #region Trading Andrey Ukraine 20 profit 100 loss results
                //Decimal res = trades.Sum(p => p.Result);
                //int zero = trades.Count(p => p.Result == 0);


                //grv_Sessions.DataSource = trades;




                //Stream streamTradesForAndKievA2 = File.Open(String.Format("TradesForAndKievA2_sl{0}.xml",(stopLoss*10000).ToString()), FileMode.Create);

                //System.Xml.Serialization.XmlSerializer xTradesForAndKievA2 = new System.Xml.Serialization.XmlSerializer(trades.GetType());
                //xTradesForAndKievA2.Serialize(streamTradesForAndKievA2, trades);
                //streamTradesForAndKievA2.Close();

                //Stream streamHCandlesForAndKievA2 = File.Open("HCandlesForAndKievA2.xml", FileMode.Create);

                //List<Tick> h1 = new List<Tick>();
                //h1=HTicks.Where(p=>p!=null).ToList<Tick>();
                //System.Xml.Serialization.XmlSerializer HCandlesForAndKievA2 = new System.Xml.Serialization.XmlSerializer(h1.GetType());
                //HCandlesForAndKievA2.Serialize(streamHCandlesForAndKievA2, h1);
                //streamHCandlesForAndKievA2.Close();
                #endregion

                #region Gaps

                Stream streamGaps = File.Open(String.Format("Gaps_Alpari_{0}-{1}.xml", ticks[0].Time.ToShortDateString().Replace("/", ""), ticks[ticks.Count - 1].Time.ToShortDateString().Replace("/", "")), FileMode.Create);

                System.Xml.Serialization.XmlSerializer xmlSerGaps = new System.Xml.Serialization.XmlSerializer(gaps.GetType());
                xmlSerGaps.Serialize(streamGaps, gaps);
                streamGaps.Close();

                #endregion
            }
        }

        public void PrepareVariants(Session session)
        {
            //string pr3 = "OLAHC;OHALC;OHALC";

            List<Session> s1 = sessions.FindAll(y => y.prev3 == session.prev3 && !String.IsNullOrEmpty(y.next1));

            //int c = 0;
            //{
            //    foreach (Session s2 in s1)
            //    {
            //        if (s2.prev3 == session.prev3)
            //            c++;
            //    }
            //}

            StringBuilder variantsToDisplay = new StringBuilder();
            List<string> listFoAnswers = new List<string>();
            decimal percent = 0;
            decimal occasions = 0;
            decimal avgWidth = 0;
            decimal avgShift = 0;

            variantsToDisplay.AppendLine(String.Format("Для типа {0}:", session.prev3));

            foreach (Session s in s1)
            {
                if (!listFoAnswers.Contains(s.next1))
                {
                    percent = 0;
                    avgWidth = 0;
                    occasions = 0;
                    avgShift = 0;

                    List<Session> sDetails = s1.FindAll(z => z.next1 == s.next1);
                    avgWidth = Math.Round((sDetails.Average(avg => avg.next1Width)), 2);
                    occasions = (decimal)sDetails.Count / s1.Count;
                    percent = Math.Round(occasions, 4) * 100;
                    avgShift = Math.Round((sDetails.Average(avg => avg.next1AvgShift)), 2);

                    variantsToDisplay.AppendLine(String.Format("Тип: {0}, совпадений {1}%, средняя ширина: {2} пунктов, среднее смещение среднего {3}"
                        , s.next1, percent, avgWidth.ToString(), avgShift.ToString()));
                    listFoAnswers.Add(s.next1);
                }
            }

            lbl_Variants.Text = variantsToDisplay.ToString();
        }

        public void MakeSession(int i, string place, Session session, List<Tick> ticks, List<Session> sessions, decimal open, SessionPoint high, SessionPoint low, decimal close, bool addManually=false)
        {
            if (!addManually)
            {
                session.Date = ticks[i].Time.Date;
                session.Place = place;
            }
            
            session.Open = open;
            session.High = high.Point;
            session.Low = low.Point;
            session.Close = close;
            session.Width = Math.Round((Math.Abs(high.Point - low.Point) * 10000), 2);
            

            decimal avg = 0;

            if (high.Point > low.Point)
                avg = high.Point - ((high.Point - low.Point) / 2);
            if (high.Point < low.Point)
                avg = low.Point - ((low.Point - high.Point) / 2);
            if (high == low)
                avg = high.Point;

            session.Avg = avg;

            if (sessions.Count > 0)
                session.AvgShift = Math.Round(((avg - sessions[sessions.Count - 1].Avg)*10000),2);

            string type = "";

            if (open < avg && close > avg)
            {
                if (high.TimeOfDay > low.TimeOfDay)
                    type = "OLAHC";
                if (high.TimeOfDay < low.TimeOfDay)
                    type = "OAHALAC";
                if (high.TimeOfDay == low.TimeOfDay)
                    type = "OLAHC_ONE";
            }
            if (open > avg && close > avg)
            {
                if (high.TimeOfDay > low.TimeOfDay)
                    type = "OALAHC";
                if (high.TimeOfDay < low.TimeOfDay)
                    type = "OHALAC";
                if (high.TimeOfDay == low.TimeOfDay)
                    type = "OALAHC_ONE";
            }
            if (open > avg && close < avg)
            {
                if (high.TimeOfDay > low.TimeOfDay)
                    type = "OALAHAC";
                if (high.TimeOfDay < low.TimeOfDay)
                    type = "OHALC";
                if (high.TimeOfDay == low.TimeOfDay)
                    type = "OHALC_ONE";
            }
            if (open < avg && close < avg)
            {
                if (high.TimeOfDay > low.TimeOfDay)
                    type = "OLAHAC";
                if (high.TimeOfDay < low.TimeOfDay)
                    type = "OAHALC";
                if (high.TimeOfDay == low.TimeOfDay)
                    type = "OAHALC_ONE";
            }

            session.Type = type;

            if (sessions.Count > 3)
                session.prev3 = sessions[sessions.Count - 2].Type + ";" + sessions[sessions.Count - 1].Type + ";" + session.Type;

            if (sessions.Count > 4)
            {
                sessions[sessions.Count - 1].next1 = session.Type;
                sessions[sessions.Count - 1].next1Avg = session.Avg;
                sessions[sessions.Count - 1].next1Width = session.Width;
                sessions[sessions.Count - 1].next1AvgShift = session.AvgShift;
            }

            sessions.Add(session);
            sessionsForGrid.Add(session);

            if (addManually)//while adding session manually with rebind data for list
            {
                Stream stream1 = File.Open("Sessions.xml", FileMode.Create);

                System.Xml.Serialization.XmlSerializer x1 = new System.Xml.Serialization.XmlSerializer(sessions.GetType());
                x1.Serialize(stream1, sessions);
                stream1.Close();

                //BindingList<Session> sessionsFoGrid = new BindingList<Session>();
                //sessionsFoGrid = sessions as BindingList<Session>;

                grv_Sessions.DataSource = sessionsForGrid;
            }
        }

        private void grv_Sessions_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            FollowUserLooking(e.RowIndex);
        }

        private void grv_Sessions_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            FollowUserLooking(e.RowIndex);
        }

        public void FollowUserLooking(int index)
        {
            if (index > 0)
            {
                //Session session = (Session)grv_Sessions.SelectedRows[0].DataBoundItem;
                PrepareVariants(sessions[index]);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(!String.IsNullOrEmpty(txt_ManualCheck.Text.Trim()))
            {
                Session session = new Session();
                session.prev3 = txt_ManualCheck.Text.Trim();
                PrepareVariants(session);

                txt_ManualCheck.Text = "";
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void addSessionManuallyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddNextSessionManually dlg = new AddNextSessionManually();

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                Session session = new Session();
                session.Date = dlg.dateEdit_SessionDate.Value.Date;
                session.Place = dlg.cmb_SessionPlace.SelectedValue.ToString();
                decimal open = 0;
                Decimal.TryParse(dlg.txt_Open.Text.Trim(), out open);
                
                SessionPoint high = new SessionPoint();
                //high.TimeOfDay = dlg.dateEdit_SessionMax.Value.TimeOfDay;
                decimal highValue = 0;
                Decimal.TryParse(dlg.txt_Max.Text.Trim(), out highValue);
                high.Point = highValue;

                SessionPoint low = new SessionPoint();
                //low.TimeOfDay = dlg.dateEdit_SessionMin.Value.TimeOfDay;
                decimal lowValue = 0;
                Decimal.TryParse(dlg.txt_Min.Text.Trim(), out lowValue);
                low.Point = lowValue;

                if (dlg.chk_MaxTimeMoreMinTime.Checked)
                {
                    high.TimeOfDay = new TimeSpan(8, 0, 0);
                    low.TimeOfDay = new TimeSpan(7, 0, 0);
                }
                else
                {
                    high.TimeOfDay = new TimeSpan(7, 0, 0);
                    low.TimeOfDay = new TimeSpan(8, 0, 0);
                }

                decimal close = 0;
                Decimal.TryParse(dlg.txt_Close.Text.Trim(), out close);

                MakeSession(0, "", session, ticks, sessions, open, high, low, close, addManually: true);
            }
        }


    }
}
